﻿using SoundEngine3.MIDI.Meta;
using System.Collections.Generic;

namespace ZquenceStudio3Host.DspPlugins.Synthesizers.Nodesizer.Engine.Modules.Protected
{
    [ModuleDisplay("Midi In")]
    public class MidiInModule : BaseModule
    {
        List<MidiMessage> mMidiMessages;
        System.Threading.ManualResetEvent mManual = new System.Threading.ManualResetEvent(false);
        int mPressedNotes;

        public readonly ModuleOutput MidiOut;

        public MidiInModule(ModuleManager manager)
            : base(manager)
        {
            mMidiMessages = new List<MidiMessage>();
            AddOutput(MidiOut = new ModuleOutput("Midi out", IOType.Midi, this));
            mMidiMessages = new List<MidiMessage>();
        }

        public override void Process()
        {
            if (mMidiMessages.Count > 0)
            {
                foreach (var midiMessage in mMidiMessages)
                {
                    MidiOut.AddMidiMessage(midiMessage);

                    if (midiMessage.MidiData.Status == MidiStatus.NOTE_ON)
                    {
                        mPressedNotes++;
                    }
                    else if (midiMessage.MidiData.Status == MidiStatus.NOTE_OFF)
                    {
                        mPressedNotes--;
                    }
                }
            }

            mMidiMessages.Clear();
        }

        protected override void OnProcessEvents(List<MidiMessage> midiMessages)
        {
            mMidiMessages.AddRange(midiMessages);
        }
    }
}